<template>
  <div class="app-container">
    <el-row>
    <el-col :span="20">
      <!-- 查询表单1 -->
      <el-form :model="queryParams" ref="queryForm1" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="省" prop="province">
          <el-select v-model='queryParams.province' filterable placeholder="请选择省" clearable>
            <el-option v-for='(temp,index) in mixinsProvinceList' :value="temp.name" :key='index' :label="temp.name" @click.native='mixinsProvinceChange(temp.code, 1)'/>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model='queryParams.city' filterable placeholder="请选择市(请先选择省)" clearable>
            <el-option v-for='(temp,index) in mixinsCityList' :value="temp.name" :key='index' :label="temp.name" @click.native='mixinsCityChange(temp.code, 1)'/>
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="area">
          <el-select v-model='queryParams.area' filterable placeholder="请选择区/县(请先选择市)" clearable>
            <el-option v-for='(temp,index) in mixinsAreaList' :value="temp.name" :key='index' :label="temp.name" @click.native='mixinsAreaChange(temp.code, 1)'/>
          </el-select>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-select v-model="queryParams.year" placeholder="请选择年份" clearable @change="handleQuery1">
            <el-option
              v-for="year in years"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery1">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1">重置</el-button>
        </el-form-item>
        <el-button type="primary" icon="el-icon-download" size="mini" style="position: absolute;" @click="handleExportChart1">导出</el-button>
      </el-form>

      <!-- echarts图表1 -->
      <div style="margin-left:20px">
        <div class="graph">
          <!-- 柱状图 -->
          <el-card style="height:350px">
            <div ref="echarts1" id="echarts1" style="height:280px"></div>
          </el-card>
        </div>
      </div>
    </el-col>
    </el-row>

    <el-row>
      <el-col :span="20">
        <!-- 查询表单2 -->
        <el-form :model="queryParams2" ref="queryForm2" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="省" prop="province">
            <el-select v-model='queryParams2.province' filterable placeholder="请选择省" clearable>
              <el-option v-for='(temp,index) in mixinsProvinceList' :value="temp.name" :key='index' :label="temp.name" @click.native='mixinsProvinceChange(temp.code, 2)'/>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-select v-model='queryParams2.city' filterable placeholder="请选择市(请先选择省)" clearable>
              <el-option v-for='(temp,index) in mixinsCityList' :value="temp.name" :key='index' :label="temp.name" @click.native='mixinsCityChange(temp.code, 2)'/>
            </el-select>
          </el-form-item>
          <el-form-item label="区/县" prop="area">
            <el-select v-model='queryParams2.area' filterable placeholder="请选择区/县(请先选择市)" clearable>
              <el-option v-for='(temp,index) in mixinsAreaList' :value="temp.name" :key='index' :label="temp.name" @click.native='mixinsAreaChange(temp.code, 2)'/>
            </el-select>
          </el-form-item>
          <el-form-item label="年份" prop="year">
            <el-select v-model="queryParams2.year" placeholder="请选择年份" clearable @change="handleQuery2">
              <el-option
                v-for="year in years"
                :key="year"
                :label="year"
                :value="year"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery2">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery2">重置</el-button>
          </el-form-item>
          <el-button type="primary" icon="el-icon-download" size="mini" style="position: absolute;" @click="handleExportChart2">导出</el-button>

        </el-form>

        <!-- echarts图表2 -->
        <div style="margin-left:20px">
          <div class="graph">
            <!-- 柱状图 -->
            <el-card style="height:350px">
              <div ref="echarts2" id="echarts2" style="height:280px"></div>
            </el-card>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listCertificate, getCertificate, delCertificate, addCertificate, updateCertificate } from "@/api/nongjt/certificate";
import { AreaMixins } from "@/mixins/AreaMixins";
import * as echarts from 'echarts';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

export default {
  name: "Certificate",
  mixins: [AreaMixins],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // certificatechart表格数据
      certificateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateNumber: null,
        printCount: null,
        scanCount: null,
        reportId: null,
        userId: null,
        district: null,
        year: new Date().getFullYear().toString() // 默认当年年份
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        certificateNumber: null,
        printCount: null,
        scanCount: null,
        reportId: null,
        userId: null,
        district: null,
        year: new Date().getFullYear().toString() // 默认当年年份
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        certificateNumber: [
          { required: true, message: "$comment不能为空", trigger: "blur" }
        ],
      },
      // 年份选项
      years: []
    };
  },
  created() {
    this.generateYears();
    this.getList1();
    this.getList2();
  },
  methods: {
    /** 生成年份选项 */
    generateYears() {
      const currentYear = new Date().getFullYear();
      for (let i = currentYear - 5; i <= currentYear + 5; i++) { // 生成最近10年和未来5年的年份选项
        this.years.push(i.toString());
      }
    },

    /** 查询certificatechart列表1 */
    getList1() {
      this.loading = true;
      listCertificate(this.queryParams).then(response => {
        this.certificateList1 = response.rows;
        this.total = response.total;
        this.loading = false;
        this.initChart1(); // 初始化图表1
      });
    },

    /** 查询certificatechart列表2 */
    getList2() {
      this.loading = true;
      listCertificate(this.queryParams2).then(response => {
        this.certificateList2 = response.rows;
        this.total2 = response.total;
        this.loading = false;
        this.initChart2(); // 初始化图表2
      });
    },

    /** 搜索按钮操作1 */
    handleQuery1() {
      this.queryParams.pageNum = 1;
      this.getList1();
    },

    /** 重置按钮操作1 */
    resetQuery1() {
      this.resetForm("queryForm1");
      this.handleQuery1();
    },

    /** 搜索按钮操作2 */
    handleQuery2() {
      this.queryParams2.pageNum = 1;
      this.getList2();
    },

    /** 重置按钮操作2 */
    resetQuery2() {
      this.resetForm("queryForm2");
      this.handleQuery2();
    },

    initChart1() {
      // 使用正确的 ref 引用
      var chartDom = this.$refs.echarts1;
      var myChart = echarts.init(chartDom);

      // 提取月份信息并生成所有月份的列表
      const allMonths = new Set();
      this.certificateList1.forEach(item => {
        const date = new Date(item.issueTime);
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // 月份从 0 开始，需要加 1
        const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
        allMonths.add(monthKey);
      });

      // 生成从最小月份到最大月份的所有月份列表
      const minMonth = Math.min(...Array.from(allMonths).map(month => new Date(month).getTime()));
      const maxMonth = Math.max(...Array.from(allMonths).map(month => new Date(month).getTime()));
      const monthCounts = {};

      let currentDate = new Date(minMonth);
      while (currentDate <= new Date(maxMonth)) {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1; // 月份从 0 开始，需要加 1
        const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
        monthCounts[monthKey] = 0;
        currentDate.setMonth(currentDate.getMonth() + 1);
      }

      // 按月份汇总 printCount
      this.certificateList1.forEach(item => {
        const date = new Date(item.issueTime);
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // 月份从 0 开始，需要加 1
        const monthKey = `${year}-${month.toString().padStart(2, '0')}`;
        if (monthCounts[monthKey] !== undefined) {
          monthCounts[monthKey] += item.printCount;
        }
      });

      // 提取汇总后的数据
      const xAxisData = Object.keys(monthCounts).sort();
      const seriesData = xAxisData.map(month => monthCounts[month]);

      var option = {
        title: {
          text: '合格证开具次数统计'
        },
        tooltip: {},
        legend: {
          data: ['打印次数']
        },
        xAxis: {
          type: 'category',
          data: xAxisData // 使用处理后的月份数据作为 X 轴数据
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '打印次数',
            data: seriesData,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      };
      myChart.setOption(option);
    },

    initChart2() {
      // 使用正确的 ref 引用
      var chartDom = this.$refs.echarts2;
      var myChart = echarts.init(chartDom);

      // 提取 productName 和 weight 数据
      const productData = this.certificateList2.map(item => ({
        productName: item.productName,
        weight: item.weight
      }));

      // 按照 weight 从大到小排序
      productData.sort((a, b) => b.weight - a.weight);

      // 截断数据，只保留前十个
      const topProductData = productData.slice(0, 10);

      // 提取排序后的 productName 和 weight 数据
      const xAxisData = topProductData.map(item => item.productName);
      const seriesData = topProductData.map(item => item.weight);

      var option = {
        title: {
          text: '主要农产品数量统计'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['重量']
        },
        xAxis: {
          type: 'category',
          data: xAxisData, // 使用处理后的 productName 数据作为 X 轴数据
          axisLabel: {
            interval: 0, // 强制显示所有标签
            rotate: 45 // 旋转标签以避免重叠
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '重量',
            data: seriesData,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      };
      myChart.setOption(option);
    },

    /** 导出图表数据1 */
    handleExportChart1() {
      const chartDom = this.$refs.echarts1;
      html2canvas(chartDom).then(canvas => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgProps = pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save(`certificate_chart1_${this.queryParams.year}.pdf`);
      });
    },

    /** 导出图表数据2 */
    handleExportChart2() {
      const chartDom = this.$refs.echarts2;
      html2canvas(chartDom).then(canvas => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('p', 'mm', 'a4');
        const imgProps = pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save(`certificate_chart2_${this.queryParams2.year}.pdf`);
      });
    },

  }
};
</script>
